﻿Option Strict Off

Public Module Helpers

    Public Function OpenFileInExistingExcel(filename As String) As Object
        On Error Resume Next

        Dim excelObj As Object = GetObject(, "Excel.Application")
        If Err.Number <> 0 Then
            Return False
        End If

        Err.Clear()

        excelObj.Visible = True
        excelObj.Workbooks.Open(filename)
        Dim winCount As Integer = excelObj.Parent.Windows.Count()
        excelObj.Parent.Windows(winCount).Visible = True

        '' Doesn't seem to be necessary to release obj when just a get called.
        '' Would be needed if I was calling CreateObject
        ''System.Runtime.InteropServices.Marshal.ReleaseComObject(excelObj)
        excelObj = Nothing

        Return (Err.Number = 0)
    End Function

    Public Function TryActivateOpenExcelInstance(filename As String) As Object
        On Error Resume Next
        ' http://msdn.microsoft.com/en-us/library/e9waz863(v=vs.90).aspx
        ' Set the object variable to refer to the file you want to use.
        Dim excelObj As Object = GetObject(filename)
        ' Show Excel through its Application property. 
        excelObj.Application.Visible = True
        ' Show the window containing the file.
        Dim winCount As Integer = excelObj.Parent.Windows.Count()
        excelObj.Parent.Windows(winCount).Visible = True
        ''System.Runtime.InteropServices.Marshal.ReleaseComObject(excelObj)

        excelObj = Nothing

        Return (Err.Number = 0)

    End Function

    Public Function GetExcelPathFromVB()
        Dim appXL As Object
        Dim s As String
        appXL = CreateObject("Excel.Application")
        s = appXL.Path
        appXL.Quit()
        appXL = Nothing
        Return s
    End Function

End Module
